package cc.telecomdigital.tdstock;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.os.Handler;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.activity.BaseActivity;

public class StreamerTimeoutHandler
{
	private final static String	TAG								= StreamerTimeoutHandler.class
																	.getSimpleName();
	private final static int		COUNTER_FOR_REALTIME				= 60/*30*/* 1000;			//one minutes
	private final static int		COUNTER_FOR_DELAY					= 10 * 60/* 30*/* 1000;	//10  minutes
	public final static int		LOCATION_BOTTOM_OF_SCREEN_PERCENTAGE	= 20;
	private Context			_context;
	private Handler			_handler;
	/*public static  Date _starttime ;
	public static long _cdrCounter = 0l;*/
	/*	private  LabelDialog  _labelDialog;*/
	private CloseStreamTask		_closeStreamTask;
	private static Timer		cdrTimer							= new Timer(
																	false);

	public StreamerTimeoutHandler(Context context, Handler handler)
	{
		_context = context;
		_handler = handler;
		_closeStreamTask = new CloseStreamTask();

	}

	public void startCounter( int... params)
	{
		TDStockLog.d(TAG, "params length : "  + params.length);
		
		int usedSeconds  = params[0];
		TDStockLog.d(TAG, "actual usedSeconds : "  + usedSeconds);
		
		/*	_starttime = new Date();*/
		//				if(_labelDialog != null) {
		//					_labelDialog.dismiss();
		//				}

		if (((ITDLApplication) _context.getApplicationContext())
				.isLightStreamerUnlimit())
		{
			return; //do nothing;
		}

		dismissLabelDialog();
		if (_closeStreamTask != null)
		{
			_closeStreamTask.cancel();
			_closeStreamTask = null;
		}
		
		 cancelTimer();

		_closeStreamTask = new CloseStreamTask();
		CommonDefn.DataMode dataMode = ((ITDLApplication) _context
				.getApplicationContext()).getDataMode();
		/*cdrTimer.schedule(_closeStreamTask,
				dataMode == CommonDefn.DataMode.Delay ? COUNTER_FOR_DELAY
						: COUNTER_FOR_REALTIME);*/
		//				 _cdrCounter += 60;
		
		if(dataMode == CommonDefn.DataMode.Delay )
		{
			cdrTimer.schedule(_closeStreamTask,COUNTER_FOR_DELAY);  //10 minutes
		}
		else {
			
			long leaveCdrTime =  ((ITDLApplication) _context
					.getApplicationContext()).getPageLeaveTime();
			
			long enterCdrTime = ((ITDLApplication) _context
					.getApplicationContext()).getPageEnterTimer();
			long wasteTimeInOtherPage  = 0l;  //not stay in monitor /stock page;
			if(leaveCdrTime != 0l) {
				wasteTimeInOtherPage  =    Math.abs(enterCdrTime - leaveCdrTime);
			}
			
			TDStockLog.d(TAG, "waste Time in other page:  " + (wasteTimeInOtherPage/ 1000)  );
			
			long scheduleTime = COUNTER_FOR_REALTIME;
			if( usedSeconds <=  5) {
				scheduleTime =   COUNTER_FOR_REALTIME;
			}
			else {
				
				if(leaveCdrTime== 0l) 
				{
					scheduleTime =  COUNTER_FOR_REALTIME + (COUNTER_FOR_REALTIME - (usedSeconds * 1000 ) % COUNTER_FOR_REALTIME);   //60 + the left
					
					if(scheduleTime == 120 * 1000) {
						scheduleTime  =  COUNTER_FOR_REALTIME;
					}
					
				}
				else {
					
					   //less than 1  minute
					if(usedSeconds  <= COUNTER_FOR_REALTIME) {
						if( wasteTimeInOtherPage >=  COUNTER_FOR_REALTIME - usedSeconds  * 1000) 
						{
							scheduleTime  =  COUNTER_FOR_REALTIME;
						}
						else {
							 scheduleTime  =  COUNTER_FOR_REALTIME  + ( COUNTER_FOR_REALTIME- usedSeconds * 1000  -wasteTimeInOtherPage );
							 TDStockLog.d(TAG, "actual scheduleTime in calc 0  : "  + scheduleTime/1000);
						}
						
						
					}
					else {  //more than 1 minute 
						if( wasteTimeInOtherPage >=  COUNTER_FOR_REALTIME - usedSeconds * 1000  %  COUNTER_FOR_REALTIME ) 
						{
							scheduleTime  =  COUNTER_FOR_REALTIME;
						}
						else {
							 scheduleTime  =  COUNTER_FOR_REALTIME  + ( COUNTER_FOR_REALTIME - usedSeconds * 1000  %  COUNTER_FOR_REALTIME  -wasteTimeInOtherPage );
							 TDStockLog.d(TAG, "actual scheduleTime in calc 1  : "  + scheduleTime/1000);
						}
						
					}
					
					
					
				/*	
					if(wasteTimeInOtherPage >  COUNTER_FOR_REALTIME + (COUNTER_FOR_REALTIME - (usedSeconds * 1000 ) % COUNTER_FOR_REALTIME) )    //over 60 + left
					{
						scheduleTime =  COUNTER_FOR_REALTIME;
					}
					else 
					{
						  if(usedSeconds <=  COUNTER_FOR_REALTIME) {
							  
						  }
						  else {
							  
						  }
					}*/
					
					
				}
				
				
				
			}
			
			
			
		/*	long scheduleTime = usedSeconds <=  5 ?  COUNTER_FOR_REALTIME :  ( COUNTER_FOR_REALTIME + (COUNTER_FOR_REALTIME - (usedSeconds * 1000 ) % COUNTER_FOR_REALTIME));
			TDStockLog.d(TAG, "actual scheduleTime  in old plan: "  + scheduleTime/1000);
			
			
			
			if(leaveCdrTime != 0l) {
				if(wasteTimeInOtherPage >=scheduleTime ) {
					scheduleTime = 60 * 1000;
				}
				else {
					scheduleTime =  scheduleTime - wasteTimeInOtherPage;
					
				}
			}
			
			
			if(scheduleTime < 60 * 1000) {
				scheduleTime  +=   60 * 1000;
			}*/
			
			
			if(params.length ==1) {
				((ITDLApplication) _context.getApplicationContext()).setPageLeaveTime(0);
			}
			TDStockLog.d(TAG, "actual scheduleTime : "  + scheduleTime/1000);
			cdrTimer.schedule(_closeStreamTask, scheduleTime); //1 minute ~ 2 minutes
			
		}
		
		
		
		
		

	}
	
	protected void cancelTimer(){
		if(cdrTimer != null) {
			cdrTimer.cancel();
			cdrTimer = null;
			cdrTimer = new Timer(
					false);
		}
	}
	
	
	

	public void resetCounter()
	{
		/*	_cdrCounter  = 0;
			_starttime = new Date();*/
		/*if(_labelDialog != null) {
			_labelDialog.dismiss();
		}*/
		
		cancelTimer();

		dismissLabelDialog();

		if (_closeStreamTask != null)
		{
			_closeStreamTask.cancel();
			_closeStreamTask = null;
		}

	}

	public void killCounter()
	{
		resetCounter();
	}

	class CloseStreamTask extends TimerTask
	{

		public void run()
		{
			if (_context != null && !Thread.interrupted())
			{

				try
				{

					if (_context instanceof BaseActivity)
					{
//						((ITDLApplication) _context
//								.getApplicationContext()).lightStreamerClient
//								.closeConnection();
						//((ITDLApplication) _context.getApplicationContext()).LSClient_Disconnect();
						//((BaseActivity) _context)._subscrRefs.clear();
						((ITDLApplication) _context
								.getApplicationContext())
								.setResetCDR(true);
					}

					((ITDLApplication) _context.getApplicationContext())
							.setLightStreamerConnected(false);
					if (_handler != null)
					{
						final Runnable job = new Runnable()
						{

							@Override
							public void run()
							{
								/*if( _labelDialog == null) {
									CommonDefn.DataMode dataMode = ((ITDLApplication)_context.getApplicationContext()).getDataMode();
									String topic = dataMode == CommonDefn.DataMode.Realtime ?  _context.getResources().getString(R.string.cdr_tips) :   _context.getResources().getString(R.string.light_reset_tips);
									_labelDialog = new LabelDialog(_context, topic) {

										@Override
										public void onClick(View v) {
											  if(_context  instanceof  BaseActivity) {
												  ((BaseActivity)_context).resetPage();
												   ((BaseActivity)_context).connectLightStreamerEx();
											  }

											super.onClick(v);
											//startCounter(); 
										}
										
									};
								}
								
								try {
									_labelDialog.show();
								} catch (Exception e) {
									 TDStockLog.e(TAG, "Can't show dialog for streamout!");
								}*/

								showLabelDialog();

							}

						};

						new Thread()
						{
							public void run()
							{
								_handler.post(job);
							}
						}.start();

					}

				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					TDStockLog
							.e(
									TAG,
									e.getMessage() == null ? "unknown exception happened!"
											: e.getMessage());
				}
			}
		}
	}

	protected void dismissLabelDialog()
	{
		/*if (_context instanceof BaseActivity)
		{
			((BaseActivity) _context).dismissStreamerTimeoutLabel();
			((BaseActivity) _context).onCdrResume();
			TDStockLog.d(TAG, "is dissmissing  streamer label!");
		}
		else
		{
			TDStockLog.e(TAG, "Can't dismiss streamer label!");
		}*/

	}

	protected void showLabelDialog()
	{
		/*if (((ITDLApplication) _context.getApplicationContext())
				.isLightStreamerUnlimit())
		{
			return; //do nothing;
		}
		if (_context instanceof BaseActivity)
		{
			((BaseActivity) _context).initStreamerTimeoutLabel();
			((BaseActivity) _context).showStreamerTimeoutLabel();
			((BaseActivity) _context).onCdrPause();
		}*/
	}


}
